from pathlib import Path
import argparse
import tempfile
from utils.ssh_client import Client

def print_banner(text: str, char: str = '-', width: int = 60):
    """打印美化的横幅"""
    print(f"\n{char * width}")
    print(f"{text:^{width}}")
    print(f"{char * width}\n")

def print_status(message: str, status: str = 'info'):
    """打印状态信息"""
    symbols = {
        'info': '📝',
        'success': '✅',
        'error': '❌',
        'warning': '⚠️'
    }
    print(f"{symbols.get(status, '>')} {message}")

def upload_config(ssh_config: dict, config_content: str, remote_path: str) -> str:
    """上传配置文件到远程服务器
    
    参数:
        ssh_config: SSH 连接配置字典
        config_content: 配置文件内容
        remote_path: 远程服务器上的目标路径
        
    返回:
        str: 远程配置文件路径
    """
    try:
        # 创建 SSH 客户端
        client = Client(**ssh_config)
        print_status(f"已连接到 {ssh_config['hostname']}", 'success')
        
        # 创建临时文件（确保路径不包含空格）
        temp_dir = Path(tempfile.mkdtemp(prefix='config_', dir=Path.cwd()))
        temp_file_path = temp_dir / f"{next(tempfile._get_candidate_names())}.tmp"
        print_status(f"创建临时文件: {temp_file_path}")
        
        with open(temp_file_path, 'wb') as temp_file:
            content = bytes(config_content, 'utf-8').decode('unicode_escape').encode('utf-8')
            temp_file.write(content)
        
        try:
            # 确保远程目录存在并设置正确的权限
            remote_dir = str(Path(remote_path).parent)
            print_status(f"创建远程目录: {remote_dir}")
            client.remote_command(f"sudo mkdir -p {remote_dir}")
            client.remote_command(f"sudo chown {ssh_config['username']} {remote_dir}")
            
            # 上传配置文件
            print_status("开始上传配置文件...")
            client.sftp.put(str(temp_file_path), remote_path)
            print_status(f"配置已上传到: {remote_path}", 'success')
            return remote_path
            
        finally:
            # 清理临时文件和目录
            temp_file_path.unlink(missing_ok=True)
            temp_dir.rmdir()
            print_status("清理临时文件完成")
        
    except Exception as e:
        print_status(f"配置上传失败: {str(e)}", 'error')
        raise
    finally:
        if 'client' in locals():
            client.close()

def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(description='配置文件上传工具', formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument('--data', required=True, help='配置文件内容')
    parser.add_argument('--filepath', required=True, help='远程配置文件路径，格式：/opt/项目名称/config.yml')
    parser.add_argument('--hosts', required=True, help='目标主机地址列表，多个主机用逗号分隔')
    
    return parser.parse_args()

def main():
    """主函数"""
    print_banner("配置文件上传工具")
    
    # 解析命令行参数
    args = parse_args()
    
    # 解析主机列表
    hosts = [host.strip() for host in args.hosts.split(',')]
    print_status(f"目标主机数量: {len(hosts)}")
    
    # 遍历每个主机进行配置上传
    success_count = 0
    for index, host in enumerate(hosts, 1):
        print_banner(f"处理主机 [{index}/{len(hosts)}] {host}", char='=')
        
        # 构建 SSH 配置
        ssh_config = {
            'hostname': host,
            'port': 5423,
            'username': "ubuntu",
            'private_key_file': "/home/ubuntu/.ssh/id_rsa"
        }
        
        try:
            # 上传配置文件
            upload_config(ssh_config, args.data, args.filepath)
            success_count += 1
        except Exception as e:
            print_status(f"主机 {host} 配置上传失败: {str(e)}", 'error')
    
    # 打印总结信息
    print_banner("上传任务完成")
    print_status(f"成功: {success_count}/{len(hosts)}", 'success' if success_count == len(hosts) else 'warning')

if __name__ == "__main__":
    main()